package com.gy.algorithm.carl.linklistexa;

/**
 * @BelongsProject: javabase
 * @BelongsPackage: com.gy.algorithm.carl
 * @Author: gy
 * @Date: 2024/10/22 11:30
 * @Description:
 */
public class SwapPairs24 {

    public static void main(String[] args) {
//        ListNode head5 = new ListNode(5);
        ListNode head4 = new ListNode(4, null);
        ListNode head3 = new ListNode(3, head4);
        ListNode head2 = new ListNode(2, head3);
        ListNode head1 = new ListNode(1, head2);

        ListNode listNode = swapPairs(head1);
        while (listNode != null) {
            System.out.println(listNode.val);
            listNode = listNode.next;
        }
    }

    // end
    public static ListNode swapPairs(ListNode head) {
        if(head == null || head.next == null) return head;

        ListNode dummy = new ListNode(0,head);
        ListNode cur = dummy;

        while(cur.next != null && cur.next.next != null){
            ListNode node1 = cur.next;
            ListNode node2 = cur.next.next;

            ListNode node3 = node2.next;
            node2.next = node1;
            node1.next = node3;
            cur.next = node2;
            cur = node1;
        }

        return dummy.next;
    }

    // write
    public static ListNode swapPairs1(ListNode head) {
        if(head == null || head.next == null) return head;

        ListNode cur = head.next;
        ListNode pre = head;

        while (cur != null){
            ListNode tempPre = cur.next;
            if(tempPre == null) break;

            ListNode tempCur = tempPre.next;
            if(tempCur == null) break;

            cur.next = pre;
            pre.next = tempCur;

            pre = tempPre;
            cur = tempCur;
        }

        return pre;
    }


    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
